import {Rule} from 'cascadium-formulae';
import uniformedCategories from './uniformed-categories';

import castMethods from '../cast-methods';
import expandMethods from '../expand-methods';
import targetMethods from '../target-methods';

const cols = {
  'code': {desc:'科目代码', width: 120, type:'string', isFilterable: true},
  'name': {desc:'科目名称', width: 150, type:'string', isFilterable: true},
  'type': {desc:'科目类型', width: 120, type:'string', isFilterable: true},
  'upperCate': {desc:'上级科目', width: 150, type:'string', isFilterable: true},
  'desc': {desc:'补充描述', width: 120, type:'string', isFilterable: true},
}

const proc = (data) => {
  return data;
}

const formRules = (books) => {

  const {data: UNIFORMED} = books.find(({name}) => name === 'UNIFORMED_CATEGORIES');

  const uniformedMap = UNIFORMED.succ
    .grip('curr.name')
    .map(([k, [v]]) => [k, v])
    .getDict();

  const topmost = new Rule({cast: '*', action: 'SELF'});

  const getRuleDesc = (dest) => {

    const props = {
      prop: 'curr.name',
      cast:'=',
      action: 'MOVE',
      dest,
      attr:{},
    }

    const {curr:{name}, attr:{subCate}} = dest;
    if (subCate) {
      return subCate.map(patt => ({patt, ...props}));
    } else {
      return [{patt: name, ...props}];
    }
  }

  for (const dest of UNIFORMED.succ) for (const desc of getRuleDesc(dest)) {
    new Rule(desc).moveTo(topmost);
  }

  const uncated = UNIFORMED.succ.find(({curr}) => curr.code === '0000');

  new Rule({cast: '*', action: 'MOVE', dest: uncated, attr:{}})
    .moveTo(topmost, {withProto: false, withPath: false, pushSide:'HEAD'});

  console.log(topmost);

  return topmost;
}

const evalData = (books) => {

  const {data: UNIFORMED} = books.find(({name}) => name === 'UNIFORMED_CATEGORIES');
  const {data: UNIVERSAL} = books.find(({name}) => name === 'UNIVERSAL');

  console.log('UNIVERSAL', UNIVERSAL.attr.INTEGRATED);

  if (!UNIVERSAL.attr.INTEGRATED) {
    console.warn('标准化科目: 等待总账的所有余额表及序时账上传并处理完毕后，再进行后续动作');
    return false;
  }

  const rule = formRules(books);
  
  for (let i = 0; i < UNIVERSAL.succ.length; i++) {

    rule.match(UNIVERSAL.succ[i], {castMethods, expandMethods, targetMethods});
  }
  // UNIFORMED.mergeFrom(UNIVERSAL, {type: 'indirect', rules: ruleSet});

  for (let cate of UNIFORMED.succ) {
    const {opening, closing, accrual, succ} = cate;
    try{
      succ.reduce(([o, c, a], curr) => {
        return [o.add(curr.opening), c.add(curr.closing), a.add(curr.accrual)]
      }, [opening, closing, accrual]);
    } catch {
      console.warn('PROBLEMATIC CALC', cate.curr.name)
    }
  }

  // return true;
}

export const spec = {
  name: 'UNIFORMED_CATEGORY_ASSIGN',
  desc: '分配规则',
  descAddi: 'Category Assigning Rules',
  cate: '分配规则',
  cols,
  data: proc(uniformedCategories),
  editable: true,
  eval: {
    proc: evalData,
    // next: ['CASHFLOW_INDIRECT_RULES_MAIN']
  },
  dataTool: {
    useUpdate: {
      displayName: '更新并重新导入标准化科目',
    }
  },
}
